package com.example.demoes.controller;
import com.example.demoes.entity.RestBean;
import com.example.demoes.entity.vo.request.ConfirmResetVO;
import com.example.demoes.entity.vo.request.EmailRegisterVO;
import com.example.demoes.entity.vo.request.EmailResetVO;
import com.example.demoes.service.AccountService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.Pattern;
import org.springframework.util.function.SupplierUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.function.Function;
import java.util.function.Supplier;
@Validated
@RestController
@RequestMapping("/api/auth")
public class AuthorizeController {
        @Resource
        AccountService service;
        @GetMapping("/ask-code")
       public RestBean<Void> askVerifyCode(@RequestParam @Email String email,
                                          @RequestParam @Pattern(regexp = "(register|reset)") String type,
                                          HttpServletRequest request
                                          ){

//           String message = service.registerEmailVerifyCode(type,email,request.getRemoteAddr());
//           System.out.println("askVerifyCode: "+message);
//           return message == null ?  RestBean.success() : RestBean.failure(400,message);

           return this.messageHandle(() -> service.registerEmailVerifyCode(type,email,request.getRemoteAddr()));
        }
        @PostMapping("/register")
       public RestBean<Void> register(@RequestBody @Validated EmailRegisterVO vo){
            //           String message = service.registerEmailAccount(vo);
           //           System.out.println();
            return this.messageHandle(() -> service.registerEmailAccount(vo));
        }
        @PostMapping("/reset-confirm")
        public RestBean<Void> resetConfirm(@RequestBody @Validated ConfirmResetVO vo){
            return this.messageHandle(() -> service.resetConfirm(vo));
        }

        @PostMapping("/reset-password")
        public RestBean<Void> resetPassword(@RequestBody @Validated EmailResetVO vo){
            return this.messageHandle(() -> service.resetEmailAccountPassword(vo));
        }
        private <T> RestBean<Void> messageHandle(T vo, Function<T,String> function){
            return messageHandle(() -> function.apply(vo));
        }
        private RestBean<Void> messageHandle(Supplier<String> action){
             String message = action.get();
             return message == null ? RestBean.success() : RestBean.failure(400,message);
       }
}
